﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Rud.Holmgren.TabulexLib.Common
{
    public static class HttpExtensions
    {
        public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
        {
            var taskComplete = new TaskCompletionSource<Stream>();
            request.BeginGetRequestStream(ar =>
            {
                Stream requestStream = request.EndGetRequestStream(ar);
                taskComplete.TrySetResult(requestStream);
            }, request);
            return taskComplete.Task;
        }

        public static IPromise<Stream> TryGetRequestStream(this HttpWebRequest request)
        {
            var retval = new Deferred<Stream>();

            request.BeginGetRequestStream(ar =>
            {
                try
                {
                    retval.Resolve(request.EndGetRequestStream(ar));
                }
                catch (Exception e)
                {
                    retval.Reject(e);
                }
            }, null);

            return retval;
        }


        public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
        {
            var taskComplete = new TaskCompletionSource<HttpWebResponse>();
            
            request.BeginGetResponse(asyncResponse =>
            {
                try
                {
                    HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
                    HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
                    taskComplete.TrySetResult(someResponse);
                }
                catch (WebException webExc)
                {
                    HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
                    taskComplete.TrySetResult(failedResponse);
                }
            }, request);

            return taskComplete.Task;
        }

        public static IPromise<HttpWebResponse> TryGetResponse(this HttpWebRequest request)
        {
            var retval = new Deferred<HttpWebResponse>();

            request.BeginGetResponse(ar =>
            {
                try
                {
                    retval.Resolve(request.EndGetResponse(ar) as HttpWebResponse);
                }
                catch (Exception e)
                {
                    retval.Reject(e);
                }
            }, null);

            return retval;

        }
    }
}
